package com.ling.luo.trade.utils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Iterator;
import java.util.Set;

/**
 * 数据校验工具类
 * @author zhanglinfeng
 */
public class ValidatorUtils {

	private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();


	/**
	 * 执行数据校验
	 * @param bean
	 */
	public static void doValidate(Object bean) {
		Set<ConstraintViolation<Object>> result = validator.validate(bean);
		if (!result.isEmpty()) {
			StringBuilder sb = new StringBuilder();
			Iterator it = result.iterator();

			while (it.hasNext()) {
				ConstraintViolation violation = (ConstraintViolation) it.next();
				sb.append("[").append(violation.getPropertyPath()).append("-").append(violation.getMessage()).append("]");
				if (it.hasNext()) {
					sb.append(";");
				}
			}
			throw new RuntimeException(sb.toString());
		}
	}

}
